package com.tencent.wxcloudrun.service.business.fangdong;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tencent.wxcloudrun.config.CustomException;
import com.tencent.wxcloudrun.config.UserContext;
import com.tencent.wxcloudrun.pojo.bo.HouseStatusEnum;
import com.tencent.wxcloudrun.pojo.bo.NoticeConstant;
import com.tencent.wxcloudrun.pojo.bo.SonStateZuFangEnum;
import com.tencent.wxcloudrun.pojo.dto.req.RejectOrAgreeReq;
import com.tencent.wxcloudrun.pojo.dto.resp.*;
import com.tencent.wxcloudrun.pojo.po.*;
import com.tencent.wxcloudrun.service.*;
import com.tencent.wxcloudrun.service.business.NoticeService;
import com.tencent.wxcloudrun.service.business.zuke.CurHouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LandTodoService {

    @Resource
    private XApplyMiddleService xApplyMiddleService;

    @Resource
    private XHouseInfoService xHouseInfoService;

    @Resource
    private XPersonInfoService xPersonInfoService;

    @Resource
    private XFeeManageSonService xFeeManageSonService;

    @Resource
    private XFeeManageMasterService xFeeManageMasterService;

    @Resource
    private XHelpmateInfoService xHelpmateInfoService;

    @Resource
    private NoticeService noticeService;

    @Resource
    private XTodoInfoService xTodoInfoService;

    @Resource
    private XLeaseMiddleService xLeaseMiddleService;

    @Resource
    private XContractManageService xContractManageService;

    @Resource
    private CurHouseService curHouseService;

    @Resource
    private com.tencent.wxcloudrun.service.business.ContractAsyncService contractAsyncService;

    public static int calculateAgeFromIdCard(String idCard) {
        // 验证身份证号基本格式
        if (idCard == null || idCard.length() != 18) {
            throw new IllegalArgumentException("身份证号必须为18位");
        }
        // 提取出生日期部分（第7到14位）
        String birthDateStr = idCard.substring(6, 14);
        try {
            // 解析出生日期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 计算年龄
            return Period.between(birthDate, currentDate).getYears();
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("无效的出生日期格式", e);
        }
    }

    public static boolean isValidNumber(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 检查是否为纯数字（允许前导零）
        if (!str.matches("\\d+")) {
            return false;
        }
        try {
            int num = Integer.parseInt(str);
            // 检查数字范围和前导零（如"01"）
            return num >= 1 && num <= 28 && str.equals(String.valueOf(num));
        } catch (NumberFormatException e) {
            return false; // 转换失败说明不是有效整数
        }
    }

    public List<LandHouseApplyPageResp> houseApplyPage(String var) {
        String openId = UserContext.getOpenId();
        // 获取当前房东所有的被申请的租房信息
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if ("tenant".equals(var)) {
            xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getTenantId, openId);
        }
        if ("land".equals(var)) {
            xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getLandId, openId);
        }
        List<XApplyMiddle> xApplyMiddleList = xApplyMiddleService.list(xApplyMiddleLambdaQueryWrapper);
        if (CollUtil.isEmpty(xApplyMiddleList)) {
            return new ArrayList<>();
        }
        List<LandHouseApplyPageResp> respList = new ArrayList<>();
        Map<String, List<XApplyMiddle>> collect = xApplyMiddleList.stream().collect(Collectors.groupingBy(XApplyMiddle::getHouseId));
        // 一个个房子进行处理
        collect.forEach((houseId, value) -> {
            LambdaQueryWrapper<XHouseInfo> xHouseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xHouseInfoLambdaQueryWrapper.eq(XHouseInfo::getHouseId, houseId);
            XHouseInfo houseInfo = xHouseInfoService.getOne(xHouseInfoLambdaQueryWrapper);
            LandHouseApplyPageResp landHouseApplyPageResp = new LandHouseApplyPageResp();
            landHouseApplyPageResp.setTitle(houseInfo.getHouseName() + "_" + houseInfo.getFloor() + "楼_" + houseInfo.getMouthMoney().toPlainString() + "元");
            landHouseApplyPageResp.setHouseId(houseId);
            ArrayList<LandHouseApplyPageResp.SonData> dataArrayList = new ArrayList<>();
            for (XApplyMiddle applyMiddle : value) {
                LandHouseApplyPageResp.SonData sonData = new LandHouseApplyPageResp.SonData();
                LambdaQueryWrapper<XPersonInfo> xPersonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonId, applyMiddle.getTenantId());
                xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonType, "tenant");
                XPersonInfo personInfo = xPersonInfoService.getOne(xPersonInfoLambdaQueryWrapper);
                sonData.setTenantInfo(personInfo.getCardName() + "_" + personInfo.getSex() + "_" + applyMiddle.getPersonNum() + "人");
                List<LandHouseApplyPageResp.LastData> lastDataList = new ArrayList<>();
                LandHouseApplyPageResp.LastData lastData1 = new LandHouseApplyPageResp.LastData();
                lastData1.setId(applyMiddle.getSonOneId());
                lastData1.setState(applyMiddle.getSonOneState());
                lastData1.setInfo(applyMiddle.getSonOneInfo());
                LandHouseApplyPageResp.LastData lastData2 = new LandHouseApplyPageResp.LastData();
                lastData2.setId(applyMiddle.getSonTwoId());
                lastData2.setState(applyMiddle.getSonTwoState());
                lastData2.setInfo(applyMiddle.getSonTwoInfo());
                LandHouseApplyPageResp.LastData lastData3 = new LandHouseApplyPageResp.LastData();
                lastData3.setId(applyMiddle.getSonThreeId());
                lastData3.setState(applyMiddle.getSonThreeState());
                lastData3.setInfo(applyMiddle.getSonThreeInfo());
                LandHouseApplyPageResp.LastData lastData4 = new LandHouseApplyPageResp.LastData();
                lastData4.setId(applyMiddle.getSonFourId());
                lastData4.setState(applyMiddle.getSonFourState());
                lastData4.setInfo(applyMiddle.getSonFourInfo());
                lastDataList.add(lastData1);
                lastDataList.add(lastData2);
                lastDataList.add(lastData3);
                lastDataList.add(lastData4);
                sonData.setLastDataList(lastDataList);
                dataArrayList.add(sonData);
            }
            landHouseApplyPageResp.setSonDataList(dataArrayList);
            respList.add(landHouseApplyPageResp);
        });
        return respList;
    }

    public GetTenantInfoResp getTenantInfo(String id) {
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getSonOneId, id);
        XApplyMiddle one = xApplyMiddleService.getOne(xApplyMiddleLambdaQueryWrapper);
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonId, one.getTenantId());
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonType, "tenant");
        XPersonInfo personInfo = xPersonInfoService.getOne(xPersonInfoLambdaQueryWrapper);
        GetTenantInfoResp getTenantInfoResp = new GetTenantInfoResp();
        getTenantInfoResp.setName(personInfo.getCardName());
        getTenantInfoResp.setSex(personInfo.getSex());
        getTenantInfoResp.setAge(calculateAgeFromIdCard(personInfo.getCardId()));
        getTenantInfoResp.setNum(one.getPersonNum());
        getTenantInfoResp.setPhone(personInfo.getPhone());
        getTenantInfoResp.setWantTime(one.getLiveNum() + " " + one.getLiveYmd());
        getTenantInfoResp.setApplyTime(DateUtil.format(one.getCreateTime(), DatePattern.NORM_DATETIME_FORMAT));
        return getTenantInfoResp;
    }

    public GetZuFangDataResp getZuFangData(String id) {
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getSonTwoId, id);
        XApplyMiddle one = xApplyMiddleService.getOne(xApplyMiddleLambdaQueryWrapper);
        GetZuFangDataResp getZuFangDataResp = new GetZuFangDataResp();
        getZuFangDataResp.setMouthFee(one.getMouthFee());
        getZuFangDataResp.setDeposit(one.getDeposit());
        getZuFangDataResp.setManageFee(one.getManageFee());
        getZuFangDataResp.setWaterPrice(one.getWaterPrice());
        getZuFangDataResp.setPowerPrice(one.getPowerPrice());
        getZuFangDataResp.setGasPrice(one.getGasPrice());
        getZuFangDataResp.setHouseRemark(one.getHouseRemark());
        getZuFangDataResp.setFeeRemark(one.getFeeRemark());
        getZuFangDataResp.setRentType(one.getRentType());
        getZuFangDataResp.setPayFeeDate(one.getPayFeeDate());
        return getZuFangDataResp;
    }

    @Transactional(rollbackFor = Exception.class)
    public String rejectOrAgree(String id, String state, String reason) {
        XApplyMiddle xApplyMiddle = new XApplyMiddle();
        xApplyMiddle.setSonTwoState("1".equals(state) ? SonStateZuFangEnum.SUCCESS.getValue() : SonStateZuFangEnum.FAILED.getValue());
        // 有可能此时是租客拒绝之后的再次由房东点击确认，所以要重置节点三为默认状态
        xApplyMiddle.setSonThreeState(SonStateZuFangEnum.WAIT.getValue());
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getSonTwoId, id);
        xApplyMiddleService.update(xApplyMiddle, xApplyMiddleLambdaQueryWrapper);
        XApplyMiddle applyMiddle = xApplyMiddleService.getOne(xApplyMiddleLambdaQueryWrapper);
        if ("1".equals(state) && StrUtil.isBlank(applyMiddle.getRentType())) {
            throw new CustomException("未选择收租方式！");
        }
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getLandlordId, applyMiddle.getLandId());
        xHelpmateInfoLambdaQueryWrapper.like(XHelpmateInfo::getHouseList, applyMiddle.getHouseId());
        List<XHelpmateInfo> list = xHelpmateInfoService.list(xHelpmateInfoLambdaQueryWrapper);
        // 找出租客的个人信息
        LambdaQueryWrapper<XPersonInfo> xPersonInfoTenant = new LambdaQueryWrapper<>();
        xPersonInfoTenant.eq(XPersonInfo::getPersonId, applyMiddle.getTenantId());
        xPersonInfoTenant.eq(XPersonInfo::getPersonType, "tenant");
        XPersonInfo tenantInfo = xPersonInfoService.getOne(xPersonInfoTenant);
        // 找出房东的个人信息
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLand = new LambdaQueryWrapper<>();
        xPersonInfoLand.eq(XPersonInfo::getPersonId, applyMiddle.getLandId());
        xPersonInfoLand.eq(XPersonInfo::getPersonType, "landlord");
        XPersonInfo landInfo = xPersonInfoService.getOne(xPersonInfoTenant);
        int helpFlag = 0; // 0表示没有助理，1表示有助理
        if (CollUtil.isNotEmpty(list)) { // 表明这间房子有助理在管理，甚至可能有多个，给他们发送通知
            for (XHelpmateInfo xHelpmateInfo : list) {
                ++helpFlag;
                noticeService.createNoticeByOpenid(xHelpmateInfo.getHelpmateId(), "helpmate",
                        NoticeConstant.APPLY_HOUSE_TWO_HELP_TITLE,
                        String.format(NoticeConstant.APPLY_HOUSE_TWO_HELP_CONTENT, "1".equals(state) ? "同意" : "拒绝",
                                "1".equals(state) ? "无" : reason + "，该条申请已自动删除", tenantInfo.getCardName(), tenantInfo.getPhone()));
            }
        }
        // 给这个房子的房东发送一个通知
        noticeService.createNoticeByOpenid(applyMiddle.getLandId(), "land",
                NoticeConstant.APPLY_HOUSE_TWO_LAND_TITLE,
                String.format(NoticeConstant.APPLY_HOUSE_TWO_LAND_CONTENT, "1".equals(state) ? "同意" : "拒绝",
                        "1".equals(state) ? "无" : reason + "，该条申请已自动删除", tenantInfo.getCardName(), (helpFlag == 0 ? tenantInfo.getPhone() : tenantInfo.getPhone() + "，该信息已同步至助理")));
        // 给租客生成一个通知
        noticeService.createNoticeByOpenid(tenantInfo.getPersonId(), "tenant",
                NoticeConstant.APPLY_HOUSE_TWO_TENANT_TITLE,
                String.format(NoticeConstant.APPLY_HOUSE_TWO_TENANT_CONTENT, "1".equals(state) ? "同意" : "拒绝",
                        "1".equals(state) ? "无" : reason + "，该条申请已自动删除", (helpFlag == 0 ? landInfo.getCardName() : list.get(0).getAlias()),
                        (helpFlag == 0 ? landInfo.getPhone() : list.get(0).getHelpPhone())));
        // 如果是拒绝，这条申请记录要删除
        if ("2".equals(state)) {
            LambdaQueryWrapper<XApplyMiddle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(XApplyMiddle::getApplyId, applyMiddle.getApplyId());
            xApplyMiddleService.remove(lambdaQueryWrapper);
            LambdaQueryWrapper<XTodoInfo> xTodoInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xTodoInfoLambdaQueryWrapper.eq(XTodoInfo::getTodoThing, applyMiddle.getApplyId());
            xTodoInfoService.remove(xTodoInfoLambdaQueryWrapper);
        }
        return "success";
    }

    @Transactional(rollbackFor = Exception.class)
    public ContractGenerateResp rejectOrAgreeWithData(RejectOrAgreeReq req) {
        // 如果是同意操作，先更新收租方式信息
        if ("1".equals(req.getState())) {
            // 验证收租方式数据
            if (StrUtil.isNotBlank(req.getPayFeeDate()) && !isValidNumber(req.getPayFeeDate())) {
                throw new CustomException("固定日期收租的方式只能输入1到28的数字。");
            }

            // 更新收租方式信息
            XApplyMiddle xApplyMiddle = new XApplyMiddle();
            xApplyMiddle.setMouthFee(req.getMouthFee());
            xApplyMiddle.setDeposit(req.getDeposit());
            xApplyMiddle.setManageFee(req.getManageFee());
            xApplyMiddle.setWaterPrice(req.getWaterPrice());
            xApplyMiddle.setPowerPrice(req.getPowerPrice());
            xApplyMiddle.setGasPrice(req.getGasPrice());
            xApplyMiddle.setHouseRemark(req.getHouseRemark());
            xApplyMiddle.setFeeRemark(req.getFeeRemark());
            xApplyMiddle.setUpdateTime(new Date());
            xApplyMiddle.setRentType(req.getRentType());
            xApplyMiddle.setPayFeeDate(req.getPayFeeDate());

            LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getSonTwoId, req.getId());
            xApplyMiddleService.update(xApplyMiddle, xApplyMiddleLambdaQueryWrapper);
        }

        // 调用原有的同意/拒绝逻辑
        String result = rejectOrAgree(req.getId(), req.getState(), req.getReason());

        // 如果是同意操作，异步生成合同并返回任务ID
        if ("1".equals(req.getState())) {
            try {
                // 获取申请信息来获取sonThreeId
                LambdaQueryWrapper<XApplyMiddle> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(XApplyMiddle::getSonTwoId, req.getId());
                XApplyMiddle applyMiddle = xApplyMiddleService.getOne(queryWrapper);

                if (applyMiddle != null) {
                    // 提交异步合同生成任务
                    String taskId = contractAsyncService.submitContractGenerateTask(applyMiddle.getSonThreeId());
                    return new ContractGenerateResp(taskId, "PENDING", "合同生成任务已提交，正在后台处理中");
                }
            } catch (Exception e) {
                log.error("提交合同生成任务失败, applyId: {}, error: {}", req.getId(), e.getMessage(), e);
                // 即使合同生成失败，也返回成功，让节点流程继续
            }
        }

        return new ContractGenerateResp("", "SUCCESS", result);
    }

    public FeeDataResp feeList(String id) {
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getSonFourId, id);
        XApplyMiddle xApplyMiddleServiceOne = xApplyMiddleService.getOne(xApplyMiddleLambdaQueryWrapper);
        FeeDataResp feeDataResp = new FeeDataResp();
        feeDataResp.setMouthFee(xApplyMiddleServiceOne.getMouthFee());
        feeDataResp.setManageFee(xApplyMiddleServiceOne.getManageFee());
        feeDataResp.setDeposit(xApplyMiddleServiceOne.getDeposit());
        BigDecimal add = NumberUtil.add(xApplyMiddleServiceOne.getMouthFee(), xApplyMiddleServiceOne.getManageFee(), xApplyMiddleServiceOne.getDeposit());
        feeDataResp.setFeeSum(add);
        return feeDataResp;
    }

    @Transactional(rollbackFor = Exception.class)
    public String handConfirm(String sonFourId) {
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getSonFourId, sonFourId);
        XApplyMiddle xApplyMiddleServiceOne = xApplyMiddleService.getOne(xApplyMiddleLambdaQueryWrapper);

        // 在正式签约时异步生成正式合同（使用新模板）
        try {
            log.info("开始异步生成正式合同, sonThreeId: {}", xApplyMiddleServiceOne.getSonThreeId());
            contractAsyncService.submitContractGenerateTaskForFormalSign(xApplyMiddleServiceOne.getSonThreeId());
        } catch (Exception e) {
            log.error("提交正式合同生成任务失败, sonThreeId: {}, error: {}", xApplyMiddleServiceOne.getSonThreeId(), e.getMessage(), e);
            // 即使合同生成失败，也让业务流程继续
        }
        // 删除租房中间管理表与这个房子相关的所有申请
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleDel = new LambdaQueryWrapper<>();
        xApplyMiddleDel.eq(XApplyMiddle::getHouseId, xApplyMiddleServiceOne.getHouseId());
        xApplyMiddleService.remove(xApplyMiddleDel);
        LambdaQueryWrapper<XTodoInfo> xTodoInfoDelTenant = new LambdaQueryWrapper<>();
        xTodoInfoDelTenant.eq(XTodoInfo::getTodoId, xApplyMiddleServiceOne.getTenantTodoId());
        xTodoInfoService.remove(xTodoInfoDelTenant);
        LambdaQueryWrapper<XTodoInfo> xTodoInfoDelLand = new LambdaQueryWrapper<>();
        xTodoInfoDelLand.eq(XTodoInfo::getTodoId, xApplyMiddleServiceOne.getLandTodoId());
        xTodoInfoService.remove(xTodoInfoDelLand);
        // 修改房屋状态
        LambdaQueryWrapper<XHouseInfo> xHouseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHouseInfoLambdaQueryWrapper.eq(XHouseInfo::getHouseId, xApplyMiddleServiceOne.getHouseId());
        XHouseInfo houseInfo = new XHouseInfo();
        houseInfo.setHouseState(HouseStatusEnum.RENT.getValue());
        xHouseInfoService.update(houseInfo, xHouseInfoLambdaQueryWrapper);
        return "success";
    }

    public List<LeaseApplyListResp> leaseApplyList(String var) {
        String openId = UserContext.getOpenId();
        LambdaQueryWrapper<XLeaseMiddle> xLeaseMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if ("tenant".equals(var)) {
            xLeaseMiddleLambdaQueryWrapper.eq(XLeaseMiddle::getTenantId, openId);
        }
        // 检查当前用户是不是助理，只能给助理看有权限管理的房屋信息
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getHelpmateId, openId);
        List<XHelpmateInfo> xHelpmateInfos = xHelpmateInfoService.list(xHelpmateInfoLambdaQueryWrapper);
        if (CollUtil.isNotEmpty(xHelpmateInfos)) { // 当前用户是助理
            List<String> stringList = JSON.parseArray(xHelpmateInfos.get(0).getHouseList(), String.class);
            xLeaseMiddleLambdaQueryWrapper.eq(XLeaseMiddle::getLandId, xHelpmateInfos.get(0).getLandlordId());
            xLeaseMiddleLambdaQueryWrapper.in(XLeaseMiddle::getHouseId, stringList);
        }
        if (CollUtil.isEmpty(xHelpmateInfos) && "land".equals(var)) { // 纯正的房东用户
            xLeaseMiddleLambdaQueryWrapper.eq(XLeaseMiddle::getLandId, openId);
        }
        List<XLeaseMiddle> leaseMiddleList = xLeaseMiddleService.list(xLeaseMiddleLambdaQueryWrapper);
        List<LeaseApplyListResp> respList = new ArrayList<>();
        if (CollUtil.isEmpty(leaseMiddleList)) {
            return respList;
        }
        for (XLeaseMiddle leaseMiddle : leaseMiddleList) {
            LeaseApplyListResp applyListResp = new LeaseApplyListResp();
            applyListResp.setLeaseId(leaseMiddle.getLeaseId());
            applyListResp.setHouseId(leaseMiddle.getHouseId());
            LambdaQueryWrapper<XPersonInfo> xPersonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonId, leaseMiddle.getTenantId());
            xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonType, "tenant");
            XPersonInfo infoServiceOne = xPersonInfoService.getOne(xPersonInfoLambdaQueryWrapper);
            applyListResp.setLeftUp(infoServiceOne.getCardName());
            applyListResp.setLeftDown(DateUtil.format(leaseMiddle.getCreateTime(), DatePattern.NORM_DATETIME_FORMAT));
            LambdaQueryWrapper<XHouseInfo> xHouseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xHouseInfoLambdaQueryWrapper.eq(XHouseInfo::getHouseId, leaseMiddle.getHouseId());
            XHouseInfo serviceOne = xHouseInfoService.getOne(xHouseInfoLambdaQueryWrapper);
            applyListResp.setRight(serviceOne.getHouseName());
            respList.add(applyListResp);
        }
        return respList;
    }

    public String leaseGetTenantPhone(String leaseId) {
        LambdaQueryWrapper<XLeaseMiddle> xLeaseMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xLeaseMiddleLambdaQueryWrapper.eq(XLeaseMiddle::getLeaseId, leaseId);
        XLeaseMiddle leaseMiddleServiceOne = xLeaseMiddleService.getOne(xLeaseMiddleLambdaQueryWrapper);
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonType, "tenant");
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonId, leaseMiddleServiceOne.getTenantId());
        XPersonInfo infoServiceOne = xPersonInfoService.getOne(xPersonInfoLambdaQueryWrapper);
        return infoServiceOne.getPhone();
    }

    public LeaseDetailResp leaseDetail(String leaseId) {
        LambdaQueryWrapper<XLeaseMiddle> xLeaseMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xLeaseMiddleLambdaQueryWrapper.eq(XLeaseMiddle::getLeaseId, leaseId);
        XLeaseMiddle leaseMiddleServiceOne = xLeaseMiddleService.getOne(xLeaseMiddleLambdaQueryWrapper);
        LeaseDetailResp leaseDetailResp = new LeaseDetailResp();
        leaseDetailResp.setHouseId(leaseMiddleServiceOne.getHouseId());
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonType, "tenant");
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonId, leaseMiddleServiceOne.getTenantId());
        XPersonInfo infoServiceOne = xPersonInfoService.getOne(xPersonInfoLambdaQueryWrapper);
        leaseDetailResp.setTenantName(infoServiceOne.getCardName());
        LambdaQueryWrapper<XFeeManageMaster> xFeeManageMasterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xFeeManageMasterLambdaQueryWrapper.eq(XFeeManageMaster::getBusinessId, leaseMiddleServiceOne.getFeeMasterId());
        XFeeManageMaster masterServiceOne = xFeeManageMasterService.getOne(xFeeManageMasterLambdaQueryWrapper);
        leaseDetailResp.setSignTime(DateUtil.format(masterServiceOne.getCreateTime(), DatePattern.NORM_DATETIME_FORMAT));
        leaseDetailResp.setTotalDays(masterServiceOne.getLiveNum() + " " + masterServiceOne.getLiveYmd());
        DateTime endDate = null;
        if (masterServiceOne.getLiveYmd().equals("日")) {
            endDate = DateUtil.offsetDay(masterServiceOne.getCreateTime(), masterServiceOne.getLiveNum());
        }
        if (masterServiceOne.getLiveYmd().equals("月")) {
            endDate = DateUtil.offsetMonth(masterServiceOne.getCreateTime(), masterServiceOne.getLiveNum());
        }
        if (masterServiceOne.getLiveYmd().equals("年")) {
            endDate = DateUtil.offsetMonth(masterServiceOne.getCreateTime(), masterServiceOne.getLiveNum() * 12);
        }
        long between = DateUtil.between(masterServiceOne.getCreateTime(), endDate, DateUnit.DAY);
        leaseDetailResp.setRemainDays(String.valueOf(between));
        leaseDetailResp.setRentDays(String.valueOf(DateUtil.between(masterServiceOne.getCreateTime(), new Date(), DateUnit.DAY)));
        leaseDetailResp.setMonthRent(masterServiceOne.getMouthFee().toPlainString());
        leaseDetailResp.setManageFee(masterServiceOne.getManageFee().toPlainString());
        leaseDetailResp.setDepo(masterServiceOne.getDeposit().toPlainString());
        LambdaQueryWrapper<XHouseInfo> xHouseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHouseInfoLambdaQueryWrapper.eq(XHouseInfo::getHouseId, masterServiceOne.getHouseId());
        XHouseInfo one = xHouseInfoService.getOne(xHouseInfoLambdaQueryWrapper);
        leaseDetailResp.setHouseName(one.getHouseName());
        return leaseDetailResp;
    }

    @Transactional
    public String dealLeaseApply(String leaseId, String dealType) {
        String openId = UserContext.getOpenId();
        LambdaQueryWrapper<XLeaseMiddle> xLeaseMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xLeaseMiddleLambdaQueryWrapper.eq(XLeaseMiddle::getLeaseId, leaseId);
        XLeaseMiddle leaseMiddleServiceOne = xLeaseMiddleService.getOne(xLeaseMiddleLambdaQueryWrapper);

        // 获取房屋信息
        LambdaQueryWrapper<XHouseInfo> xHouseInfoQueryWrapper = new LambdaQueryWrapper<>();
        xHouseInfoQueryWrapper.eq(XHouseInfo::getHouseId, leaseMiddleServiceOne.getHouseId());
        XHouseInfo houseInfo = xHouseInfoService.getOne(xHouseInfoQueryWrapper);

        // 判断当前用户是助理还是房东（参考leaseApplyList方法的实现）
        LambdaQueryWrapper<XHelpmateInfo> currentUserHelpmateQuery = new LambdaQueryWrapper<>();
        currentUserHelpmateQuery.eq(XHelpmateInfo::getHelpmateId, openId);
        List<XHelpmateInfo> currentUserHelpmateList = xHelpmateInfoService.list(currentUserHelpmateQuery);
        boolean isCurrentUserHelper = CollUtil.isNotEmpty(currentUserHelpmateList);

        // 获取租客信息
        LambdaQueryWrapper<XPersonInfo> xPersonInfoTenant = new LambdaQueryWrapper<>();
        xPersonInfoTenant.eq(XPersonInfo::getPersonId, leaseMiddleServiceOne.getTenantId());
        xPersonInfoTenant.eq(XPersonInfo::getPersonType, "tenant");
        XPersonInfo tenantInfo = xPersonInfoService.getOne(xPersonInfoTenant);

        // 获取房东信息
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLand = new LambdaQueryWrapper<>();
        xPersonInfoLand.eq(XPersonInfo::getPersonId, houseInfo.getLandlordId());
        xPersonInfoLand.eq(XPersonInfo::getPersonType, "landlord");
        XPersonInfo landInfo = xPersonInfoService.getOne(xPersonInfoLand);

        if ("1".equals(dealType)) { // 拒绝
            // 去除待办表数据
            LambdaQueryWrapper<XTodoInfo> xTodoInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xTodoInfoLambdaQueryWrapper.eq(XTodoInfo::getTodoThing, leaseMiddleServiceOne.getLeaseId());
            xTodoInfoLambdaQueryWrapper.eq(XTodoInfo::getTodoOption, "退租申请");
            xTodoInfoService.remove(xTodoInfoLambdaQueryWrapper);
            // 去除退租中间表数据
            xLeaseMiddleService.remove(xLeaseMiddleLambdaQueryWrapper);

            // 房东或助理拒绝退租时的通知
            if (isCurrentUserHelper) {
                // 当前操作者是助理，只通知房东和租客
                XHelpmateInfo currentHelper = currentUserHelpmateList.get(0);

                // 给房东发送通知
                noticeService.createNoticeByOpenid(houseInfo.getLandlordId(), "land",
                        NoticeConstant.LEASE_REJECT_LAND_TITLE,
                        String.format(NoticeConstant.LEASE_REJECT_LAND_CONTENT,
                                "助理", tenantInfo.getCardName(), tenantInfo.getPhone()));

                // 给租客发送通知（显示助理信息）
                noticeService.createNoticeByOpenid(leaseMiddleServiceOne.getTenantId(), "tenant",
                        NoticeConstant.LEASE_REJECT_TENANT_TITLE,
                        String.format(NoticeConstant.LEASE_REJECT_TENANT_CONTENT,
                                currentHelper.getAlias(), currentHelper.getHelpPhone()));

            } else {
                // 当前操作者是房东，通知房东自己和租客

                // 给房东自己发送通知
                noticeService.createNoticeByOpenid(houseInfo.getLandlordId(), "land",
                        NoticeConstant.LEASE_REJECT_LAND_TITLE,
                        String.format(NoticeConstant.LEASE_REJECT_LAND_CONTENT,
                                "您", tenantInfo.getCardName(), tenantInfo.getPhone()));

                // 给租客发送通知（显示房东信息）
                noticeService.createNoticeByOpenid(leaseMiddleServiceOne.getTenantId(), "tenant",
                        NoticeConstant.LEASE_REJECT_TENANT_TITLE,
                        String.format(NoticeConstant.LEASE_REJECT_TENANT_CONTENT,
                                landInfo.getCardName(), landInfo.getPhone()));
            }

        }
        if ("2".equals(dealType)) { // 同意
            LambdaQueryWrapper<XFeeManageMaster> xFeeManageMasterLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xFeeManageMasterLambdaQueryWrapper.eq(XFeeManageMaster::getBusinessId, leaseMiddleServiceOne.getFeeMasterId());
            XFeeManageMaster masterServiceOne = xFeeManageMasterService.getOne(xFeeManageMasterLambdaQueryWrapper);
            LambdaQueryWrapper<XContractManage> xContractManageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xContractManageLambdaQueryWrapper.eq(XContractManage::getContractId, masterServiceOne.getContractId());
            xContractManageService.remove(xContractManageLambdaQueryWrapper);
            XFeeManageMaster xFeeManageMaster = new XFeeManageMaster();
            xFeeManageMaster.setEffect("no");
            xFeeManageMaster.setUpdateTime(new Date());
            xFeeManageMasterService.update(xFeeManageMaster, xFeeManageMasterLambdaQueryWrapper);
            XHouseInfo xHouseInfo = new XHouseInfo();
            xHouseInfo.setHouseState(HouseStatusEnum.WAIT_RENT.getValue());
            xHouseInfo.setUpdateId(openId);
            xHouseInfo.setUpdateTime(new Date());
            LambdaQueryWrapper<XHouseInfo> xHouseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xHouseInfoLambdaQueryWrapper.eq(XHouseInfo::getHouseId, masterServiceOne.getHouseId());
            xHouseInfoService.update(xHouseInfo, xHouseInfoLambdaQueryWrapper);

            // 去除待办表数据
            LambdaQueryWrapper<XTodoInfo> xTodoInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xTodoInfoLambdaQueryWrapper.eq(XTodoInfo::getTodoThing, leaseMiddleServiceOne.getLeaseId());
            xTodoInfoLambdaQueryWrapper.eq(XTodoInfo::getTodoOption, "退租申请");
            xTodoInfoService.remove(xTodoInfoLambdaQueryWrapper);
            // 去除退租中间表数据
            xLeaseMiddleService.remove(xLeaseMiddleLambdaQueryWrapper);

            // 房东或助理同意退租时的通知
            if (isCurrentUserHelper) {
                // 当前操作者是助理，只通知房东和租客
                XHelpmateInfo currentHelper = currentUserHelpmateList.get(0);

                // 给房东发送通知
                noticeService.createNoticeByOpenid(houseInfo.getLandlordId(), "land",
                        NoticeConstant.LEASE_APPROVE_LAND_TITLE,
                        String.format(NoticeConstant.LEASE_APPROVE_LAND_CONTENT,
                                "助理", tenantInfo.getCardName(), tenantInfo.getPhone()));

                // 给租客发送通知（显示助理信息）
                noticeService.createNoticeByOpenid(leaseMiddleServiceOne.getTenantId(), "tenant",
                        NoticeConstant.LEASE_APPROVE_TENANT_TITLE,
                        String.format(NoticeConstant.LEASE_APPROVE_TENANT_CONTENT,
                                currentHelper.getAlias(), currentHelper.getHelpPhone()));

            } else {
                // 当前操作者是房东，通知房东自己和租客

                // 给房东自己发送通知
                noticeService.createNoticeByOpenid(houseInfo.getLandlordId(), "land",
                        NoticeConstant.LEASE_APPROVE_LAND_TITLE,
                        String.format(NoticeConstant.LEASE_APPROVE_LAND_CONTENT,
                                "您", tenantInfo.getCardName(), tenantInfo.getPhone()));

                // 给租客发送通知（显示房东信息）
                noticeService.createNoticeByOpenid(leaseMiddleServiceOne.getTenantId(), "tenant",
                        NoticeConstant.LEASE_APPROVE_TENANT_TITLE,
                        String.format(NoticeConstant.LEASE_APPROVE_TENANT_CONTENT,
                                landInfo.getCardName(), landInfo.getPhone()));
            }

        }
        return "success";
    }

    public GetTodoCountResp getTodoCount(String type) {
        GetTodoCountResp getTodoCountResp = new GetTodoCountResp();
        LambdaQueryWrapper<XTodoInfo> master = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<XTodoInfo> apply = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<XTodoInfo> tui = new LambdaQueryWrapper<>();
        master.eq(XTodoInfo::getTodoPerson, UserContext.getOpenId());
        apply.eq(XTodoInfo::getTodoPerson, UserContext.getOpenId());
        tui.eq(XTodoInfo::getTodoPerson, UserContext.getOpenId());
        if ("land".equals(type)) {
            master.eq(XTodoInfo::getTodoRole, "land");
            apply.eq(XTodoInfo::getTodoRole, "land");
            tui.eq(XTodoInfo::getTodoRole, "land");
        }
        if ("tenant".equals(type)) {
            master.eq(XTodoInfo::getTodoRole, "tenant");
            apply.eq(XTodoInfo::getTodoRole, "tenant");
            tui.eq(XTodoInfo::getTodoRole, "tenant");
        }
        long count = xTodoInfoService.count(master);
        if (count == 0) {
            return getTodoCountResp;
        }
        getTodoCountResp.setCount(Integer.parseInt(String.valueOf(count)));
        tui.eq(XTodoInfo::getTodoOption, "退租申请");
        long count1 = xTodoInfoService.count(tui);
        getTodoCountResp.setTuiCount(Integer.parseInt(String.valueOf(count1)));
        apply.eq(XTodoInfo::getTodoOption, "租房申请");
        long count2 = xTodoInfoService.count(apply);
        getTodoCountResp.setApplyCount(Integer.parseInt(String.valueOf(count2)));
        return getTodoCountResp;
    }
}
